package com.itheima.crm.controller;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itheima.crm.pojo.BaseDict;
import com.itheima.crm.pojo.Customer;
import com.itheima.crm.pojo.QueryVo;
import com.itheima.crm.service.BaseDictService;
import com.itheima.crm.service.CustomerService;
import com.itheima.crm.utils.Page;

@Controller
public class CustomerController {

	@Autowired
	private BaseDictService baseDictService;
	@Autowired
	private CustomerService customerService;
	
	@Value("${customer.source.code}")
	private String custSourceCode;
	@Value("${customer.industry.code}")
	private String custIndustryCode;
	@Value("${customer.level.code}")
	private String custLevelCode;
	
	
	@RequestMapping("/customer/list")
	public String showCustomerList(QueryVo queryVo ,Model model) throws Exception{
		//解决get请求乱码
		if (StringUtils.isNotBlank(queryVo.getCustName())) {
			queryVo.setCustName(new String(queryVo.getCustName().getBytes("iso8859-1"), "utf-8"));
		}
		System.out.println(queryVo.getCustName());
		//初始化客户来源
		List<BaseDict> custSource = baseDictService.getDictListByTypeCode(custSourceCode);
		//所属行业
		List<BaseDict> custIndustry = baseDictService.getDictListByTypeCode(custIndustryCode);
		//客户级别
		List<BaseDict> custLevel = baseDictService.getDictListByTypeCode(custLevelCode);
		////把字典信息传递给页面
		model.addAttribute("fromType", custSource);
		model.addAttribute("industryType", custIndustry);
		model.addAttribute("levelType", custLevel);
		Page<Customer> page = customerService.getCustomerList(queryVo);
		//把客户列表传递给页面
		model.addAttribute("page", page);
		//数据回显
		model.addAttribute("custName", queryVo.getCustName());
		model.addAttribute("custSource", queryVo.getCustSource());
		model.addAttribute("custIndustry", queryVo.getCustIndustry());
		model.addAttribute("custLevel", queryVo.getCustLevel());
		return "customer";
	}
	
	@RequestMapping("/customer/edit")
	@ResponseBody
	public Customer getCustomerById(Long id){
		Customer customer = customerService.getCustomerById(id);
		return customer;
	}
	
	@RequestMapping("/customer/update")
	@ResponseBody
	public void getUpdateCustomer(Customer customer){
		customerService.getUpdateCustomer(customer);
	}
	
	@RequestMapping("/customer/del")
	@ResponseBody
	public void getDeleteCustomerById(Long id){
		customerService.getDeleteCustomerById(id);
	}
}
